package com.captjack.common.util.io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * 简单文件读取写入操作
 *
 * @author Capt Jack
 * @date 2017/8/2
 */
public final class FileUtils {

    /**
     * 写入文件
     *
     * @param filePath    文件路径
     * @param bytes       字节数组
     * @param isOverwrite 是否覆盖
     * @throws IOException 异常
     */
    public static void writeByteArrayToFile(String filePath, byte[] bytes, boolean isOverwrite) throws IOException {
        File file = new File(filePath);
        // 输出流，用于写文件
        FileOutputStream fileOutputStream = null;
        try {
            if (!file.exists() && !file.createNewFile()) {
                throw new FileNotFoundException("file is not exist and try to create a new file failed！path : " + filePath);
            }
            // true代表追加，false代表覆盖
            fileOutputStream = new FileOutputStream(file, isOverwrite);
            // 写文件
            fileOutputStream.write(bytes);
        } finally {
            IoCommonUtil.closeStream(fileOutputStream);
        }
    }

    /**
     * 在文件中按行追加内容
     *
     * @param filePath  追加的文件路径
     * @param appendStr 追加的内容
     * @throws IOException 异常
     */
    public static void appendFile(String filePath, String appendStr) throws IOException {
        writeByteArrayToFile(filePath, appendStr.getBytes(Charset.defaultCharset()), true);
    }

    /**
     * 在文件中按行追加内容
     *
     * @param filePath  追加的文件路径
     * @param appendStr 追加的内容
     * @param charset   编码格式
     * @throws IOException 异常
     */
    public static void appendFile(String filePath, String appendStr, Charset charset) throws IOException {
        writeByteArrayToFile(filePath, appendStr.getBytes(charset), true);
    }

    /**
     * 按行读取文件，返回List
     *
     * @param filePath    文件路径
     * @param charsetName 编码方式
     * @return list
     */
    public static List<String> readFileByLine(String filePath, String charsetName) throws IOException {
        List<String> list = new ArrayList<>();
        // 缓冲字符流输入流
        BufferedReader bufferedReader = null;
        try {
            File file = new File(filePath);
            if (!file.isFile() && !file.exists()) {
                throw new FileNotFoundException("path is not a file or path isn't exist！path : " + filePath);
            }
            bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charsetName));
            // 二进制输入流
            String lineText;
            while ((lineText = bufferedReader.readLine()) != null) {
                list.add(lineText);
            }
            return list;
        } finally {
            IoCommonUtil.closeStream(bufferedReader);
        }
    }

}
